<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇3_投放食物</title>
    <style>
        body {
            text-align: center;
            padding: 20px;
        }

        #canvas {
            box-shadow: 0 0 10px #333;
            margin: 0 auto;
        }
    </style>
    <script>
        window.onload = function () {
            var game=new Draw();
        }
        function Draw() {
            /**@type {HTMLCanvasElement}*/
            var oCanvas = document.getElementById('canvas');//画布
            if (oCanvas.getContext) {
                var ctx = oCanvas.getContext('2d');//画笔
                var isEatFoot = false;//判断是否吃到食物false没有迟到，true吃到

                var snake = new Snake();
                snake.snakeDraw();
                var foot = setFoot();



                var timer = setInterval(animation, 300);
                //二：动画,让蛇动起来
                // window.requestAnimationFrame动画跑太快
                function animation() {
                    ctx.clearRect(0, 0, oCanvas.width, oCanvas.height);
                    snake.snakeDraw();
                    foot.draw();
                    snake.move();

                    //判断是否迟到食物
                    if (snake_footCath(snake.head, foot)) {
                        isEatFoot = true;
                        //吃成功之后刷新foot
                        foot = setFoot();

                    }

                    //判断蛇头是否与蛇身相撞，在Snake里this.body.length未定义
                    for (var i = 0; i < snake.body.length; i++) {
                        if (snake_footCath(snake.head, snake.body[i])) {
                            clearInterval(timer);
                            timer = null;
                            alert('您碰到了自己的身体，Game Over~\n3秒后游戏将重新开始');
                            setTimeout(function(){
                                game=new Draw();
                            },3000);
                        }
                    }

                    // window.requestAnimationFrame(animation);
                }

                //键盘事件
                document.onkeydown = function (ev) {
                    var ev = ev || window.event;
                    //37左，39右，38上，40下
                    switch (ev.keyCode) {
                        case 37: {
                            snake.direction = 37;
                            snake.move();
                            break;
                        };
                        case 39: {
                            snake.direction = 39;
                            snake.move();
                            break;
                        };
                        case 38: {
                            snake.direction = 38;
                            snake.move();
                            break;
                        };
                        case 40: {
                            snake.direction = 40;
                            snake.move();
                            break;
                        };
                    }
                }

                // snake.move();
                /*一、画蛇：1.蛇的组成，2.蛇头，3.蛇身*/

                //1.蛇的组成对象
                function Rect(x, y, width, height, color) {
                    this.x = x;
                    this.y = y;
                    this.width = width;
                    this.height = height;
                    this.color = color;

                    this.draw = function () {
                        ctx.fillStyle = color;
                        ctx.beginPath();
                        ctx.fillRect(this.x, this.y, this.width, this.height);
                        ctx.strokeRect(this.x, this.y, this.width, this.height);
                    }
                }

                //蛇
                function Snake() {
                    this.head = new Rect(oCanvas.width / 2 - 25, oCanvas.height / 2 - 25, 25, 26, 'red');
                    this.body = new Array();
                    this.x = this.head.x - this.head.width;//蛇身位置
                    this.direction = 39;//控制蛇的走向默认向右

                    for (var i = 0; i < 3; i++) {
                        var rect_body = new Rect(this.x, this.head.y, this.head.width, this.head.height, 'gray');
                        this.body.push(rect_body);
                        this.x -= this.head.width;
                    }

                    this.snakeDraw = function () {
                        this.head.draw();
                        for (var i = 0; i < this.body.length; i++) {
                            this.body[i].draw();
                        }
                    }

                    this.move = function () {
                        var rect = new Rect(this.head.x, this.head.y, this.head.width, this.head.height, 'gray');
                        //加头
                        this.body.splice(0, 0, rect);
                        //去尾,没吃到事务去尾，吃到不去
                        if (isEatFoot == false) {
                            this.body.pop();
                        }
                        else {
                            isEatFoot = false;
                        }

                        switch (this.direction) {
                            case 37: {
                                this.head.x -= this.head.width;
                                break;
                            }

                            case 39: {
                                this.head.x += this.head.width;
                                break;
                            }

                            case 38: {
                                this.head.y -= this.head.height;
                                break;
                            }

                            case 40: {
                                this.head.y += this.head.height;
                                break;
                            }
                        }

                        // 首尾是否相撞检测
                        // console.log('首尾检测：');
                        // for(var i=0;i<this.body.lenght;i++){//for循环未执行,body长度未定义
                        //     console.log('首尾碰撞检测：2');
                        //     if(snake_footCath(this.head,this.body[i])){
                        //         console.log('蛇头蛇身相撞');
                        //         clearInterval(timer);
                        //         timer=null;
                        //         alert('您撞到了自己,Game OVER~');
                        //     }
                        // }

                        //碰壁检测
                        if (this.head.x >= oCanvas.width || this.head.x < 0 || this.head.y < 0 ||
                            this.head.y >= oCanvas.height) {

                            clearInterval(timer);
                            timer = null;
                            alert('您撞到了墙壁，Game Over~,\n3秒后游戏将重新开始');
                            setTimeout(function(){
                                game=new Draw();
                            },3000);
                        }
                        // console.log('body长度:'+this.body.lenght);
                        for (var j = 0; j < this.body.lenght; j++) {
                            console('j' + j);
                        }
                    }

                }

                function setFoot() {
                    var isInSnake = true;//判断食物是否在蛇身上，如果在蛇身上则从新投放
                    while (isInSnake) {
                        var x = get_Random(0, oCanvas.width - snake.head.width);
                        var y = get_Random(0, oCanvas.height - snake.head.height);

                        var rect = new Rect(x, y, snake.head.width, snake.head.height, 'green');

                        //判断食物是否与蛇头重叠
                        if (snake_footCath(snake.head, rect)) {
                            isInSnake = true;
                            continue;
                        }
                        //判断食物是否与蛇身重叠
                        for (var i = 0; i < snake.body.lenght; i++) {
                            if (snake_footCath(snake.body[i], rect)) {
                                isInSnake = true;
                                continue;
                            }
                        }

                        isInSnake = false;
                        return rect;
                    }
                }
                //获取随机数
                function get_Random(min, max) {
                    return Math.round(Math.random() * (max - min) + min);
                }

                //判断食物与蛇是否重叠
                function snake_footCath(rect1, rect2) {
                    var minx1 = rect1.x;
                    var minx2 = rect2.x;

                    var maxx1 = rect1.width + minx1;
                    var maxx2 = rect2.width + minx2;

                    var miny1 = rect1.y;
                    var miny2 = rect2.y;

                    var maxy1 = rect1.height + miny1;
                    var maxy2 = rect2.height + miny2;

                    //判断矩形相交的最大最小值
                    //不考虑矩形位子，只要右边的最小x,最小y小于左边最大x最大y即碰撞

                    var minX = Math.max(minx1, minx2);
                    var minY = Math.max(miny1, miny2);
                    var maxX = Math.min(maxx1, maxx2);
                    var maxY = Math.min(maxy1, maxy2);

                    if (minX < maxX && minY < maxY) {
                      
                        return true;
                    } else {
                        return false;
                    }
                }

            } else {
                alert('你的浏览器版本太低')
            }
        }
    </script>
</head>

<body>
    <canvas id="canvas" width="800px" height="600px">
        你的浏览器版本太低，请更新~
    </canvas>
</body>

</html>